<template>
	<view>
		<cu-custom>
			<view class="cu-bar fixed"
				:style="{'height':customBarHeight + 'px','padding-top':statusBarHeight + 'px','background-color':themeConfig.primaryColor}">
				<view class="margin-left-sm text-white" @tap="tapScan()">
					<view class="cuIcon-scan" style="font-size: 45rpx;"></view>
				</view>
				<view class="search-form round flex justify-center align-center">
					<input type="text" confirm-type="search" @confirm="searchDevice" :value="searchName"
						@input="searchNameInputChange" placeholder="搜索设备名称/编号"
						placeholder-style="color: #ff0000;text-align:center;"
						style="padding-right:0rpx;text-align:center;" />
				</view>
				<view v-if="searchName != null && searchName.lenght != 0" class="text-white">
					<button class="cu-btn bg-gradual-green round margin-right-xs" @tap="searchDevice()">搜索</button>
				</view>
			</view>
		</cu-custom>
		<map :subkey="qqMapKey" id="0" ref="myMap" style="width:100vw;height:100vh;"
			 :scale="scale" :longitude="lng"
			:latitude="lat" :markers="markers" @markertap="markertap" @tap="mapTap" @regionchange="regionchange"></map>
	</view>
</template>

<script>
	import {
		showToast,
		showLoading,
		hideLoading
	} from '@/util/toast'
	import {
		listDeviceStatus,
	} from '@/util/utils'
	import * as storage from '@/util/storage'
	import myConfig from '@/myConfig'
	import * as deviceApi from '@/api/dmIot/deviceApi.ts'
	import * as systemApi from '@/api/dmIot/systemApi.ts'
	import * as ztIotApi from '@/api/dmIot/ztIotApi.ts'
	import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
	let mapContext = {}
	export default {
		name: 'DeviceMap',
		mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件)
		components: {
			
		},
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		props: {
			param: {
				type: [Number,String,Object],
				default() {
					return null;
				}
			},
		},
		data() {
			return {
				downOption: {
					use: false,
					auto: false, //是否在初始化后,自动执行downCallback; 默认true
				},
				upOption: {
					empty: {
						use: true,
						fixed: true,
						top: '10%'
					}
				},
				iconBaseUrl: myConfig.app.iconBaseUrl,
				
				searchName: null,
				showMode: '',
				selectStyle: '',
				unselectStyle: '',
				// scale: 4.5,
				scale: 8,
				// lng: null,
				// lat: null,
				lat: 23,
				lng: 113,
				markers: [],
				markerId: null,
				currentPage: 1,
				pageSize: 10,
				statusIndex: 0,
				statusList: [],
				// productList: [],
				// productSeriesList: [],
				// productAndSeriesList: [
				// 	[],
				// 	[]
				// ],
				// productAndSeriesNameList: [
				// 	[],
				// 	[]
				// ],
				// productAndSeriesIndex: [0, 0],
				// productId: null,
				// seriesId: null,
				ancestors: -1,
				treeName: "全部公司",
				treeList: [],
				multiple: false,
				selectParent: true,
				flod: true,
				deviceList: [],
				isShowDeviceList: false,
				totalDeviceNum: 0,
				// userId: storage.getUserId(),
				// companyId: storage.getCompanyId(),
				// deptId: storage.getDeptId(),
				// websiteModel: storage.getWebsiteModel(),
				qqMapKey: myConfig.app.qqMapKey,
				showLoadingMuchTip: false,
				customBarHeight: storage.getCustomBarHeight(),
				statusBarHeight: storage.getStatusBarHeight(),
				tabbarHeight: storage.getTabbarHeight(),
				screenHeight: storage.getScreenHeight(),
			}
		},
		beforeMount() {
			const primaryColor = this.$store.state.themeConfig.primaryColor
			this.selectStyle = `background:${primaryColor};color:#fff;border:2rpx solid ${primaryColor}`
			this.unselectStyle = `background:#fff;color:${primaryColor};border:2rpx solid ${primaryColor}`
		},
		created() {
			this.statusList = listDeviceStatus(this)
		},
		mounted() {
			this.init()
		},
		methods: {
			searchNameInputChange(e) {
				let searchName = e.detail.value.replace(/\s/g, '')
				this.searchName = searchName
			},
			searchDevice(){
				let searchName = this.searchName
				this.goToDeviceList(searchName)
			},
			goToDeviceList(param){
				uni.$emit("navChange","device",param)
			},
			tapScan() {
				uni.scanCode({
					success: (res) => {
						let result = res.result
						ztIotApi.bindingInsecticidalLampDevice({
							"bindingCode": result
						}).then((res) => {
							const {
								msg,
								data,
								success
							} = res
							if (success) {
								showToast("操作成功", 'none', 1000, false) //操作成功
								this.goToDeviceList()
							}
						})
					},
					fail: (res) => {
						showToast("操作失败", 'none', 1000, false) //操作失败
					}
				});
			},
			init() {
				mapContext = uni.createMapContext('myMap', this)
				this.getDeviceList()
				// this.tapMode(storage.getMapModel())
			},
			
			handleProductSeriesList(data) {
				this.productSeriesList = listProductSeries(this, data)
				this.makeProductAndSeriesNameList()
			},
			productAndSeriesColumnchange(e) {
				// console.log('修改的列为：' + e.detail.column + '，值为：' + e.detail.value)
				const column = e.detail.column
				const value = e.detail.value
				switch (column) {
					case 0: //拖动第1列
						if (value != 0) {
							this.productId = this.productList[value].productId
							this.listSeries().then((res) => {
								this.productAndSeriesIndex = [value, 0]
							})
						} else {
							this.productAndSeriesIndex = [0, 0]
						}
						break;
					case 1:
						this.productAndSeriesIndex = [this.productAndSeriesIndex[0], value]
						break
					default:
						break;
				}
				this.$forceUpdate()
			},
			productAndSeriesChange(e) {
				const index = e.detail.value
				this.productAndSeriesIndex = index
				this.productId = this.productList[index[0]].productId
				storage.setProductId(this.productId)
				this.seriesId = this.productSeriesList[index[1]].seriesId
				this.tapMode(storage.getMapModel())
			},
			statusChange(e) {
				this.statusIndex = e.detail.value
				storage.setStatusIndex(this.statusIndex)
				this.getDeviceList()
				// this.tapMode(storage.getMapModel())
			},
			resetMapParam() {
				this.markers = []
				this.markerId = null
			},
			formatStatusIndex(index) {
				return this.statusList[index]
			},
			tapMode(showMode) {
				this.resetMapParam()
				this.currentPage = 1
				this.deviceList = []
				this.showMode = showMode
				storage.setMapModel(showMode)
				switch (showMode) {
					case 'area':
						this.scale = 4.5
						this.listProvinceNum()
						break
					case 'point':
						this.scale = 8
						this.listDevice()
						break
					case 'geo':
						this.scale = 8
						this.listDeviceGEO()
						break
				}
			},
			// 显示树形选择器
			showTree() {
				this.$refs.tkitree._show();
			},
			getTreeselect() {
				systemApi.getTreeselect().then(res => {
					let data = res.data
					this.treeList = [{
						ancestors: -1,
						count: -1,
						id: -1,
						label: "全部公司",
						// checked: true,
						children: data
					}]
				})
			},
			treeConfirm(e) {
				// console.log(e)
				this.treeName = e[0].label
				this.ancestors = e[0].ancestors
				this.getDeviceList()
			},
			treeCancel(e) {
				// console.log(e)
			},
			getDeviceList() {
				showLoading(this.$t('loading'), true)
				let ancestors = this.ancestors
				let inline = this.statusList[this.statusIndex].value
				let params = {
					pageNum: 1,
					pageSize: 999
				}
				if (ancestors != -1) {
					params['ancestors'] = ancestors
				}
				if (inline != -1) {
					params['inline'] = inline
				}
				deviceApi.getDeviceList(params).then((res) => {
					const {
						code,
						msg,
						rows,
						total
					} = res
					for (var i = 0; i < rows.length; i++) {
						let {
							icon,
							typeIcon,
						} = rows[i]
						let iconImage;
						if (icon != "") {
							iconImage = this.iconBaseUrl + 'device_icon/' + icon + '.png'
						} else {
							iconImage = this.iconBaseUrl + 'device_icon/' + typeIcon + '.png'
						}
						rows[i]['iconImage'] = iconImage
					}
					this.resetMapParam()
					this.setPointMarkers(rows)
					setTimeout(() => {
						hideLoading()
					}, 0)
				})
			},
			listProvinceNum() {
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.provinceAllDeviceNum({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
						break
					case 'company':
						api = iotDeviceApi.provinceDeviceNumByCompany({
							companyId: this.companyId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
						break
					case 'dept':
						api = iotDeviceApi.provinceDeviceNumByDept({
							deptId: this.deptId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
						break
					default:
						api = iotDeviceBelongApi.provinceBelongDeviceNum({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
				}

				api.then((res) => {
					const {
						data
					} = res
					if (data) {
						this.resetMapParam()
						this.setAreaMarkers(data)
					}
				})
			},
			listCityNum() {
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.cityAllDeviceNum({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
						break
					case 'company':
						api = iotDeviceApi.cityDeviceNumByCompany({
							companyId: this.companyId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
						break
					case 'dept':
						api = iotDeviceApi.cityDeviceNumByDept({
							deptId: this.deptId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
						break
					default:
						api = iotDeviceBelongApi.cityBelongDeviceNum({
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
						})
				}
				api.then((res) => {
					const {
						data
					} = res
					if (data) {
						this.resetMapParam()
						this.setAreaMarkers(data)
					}
				})
			},
			setAreaMarkers(data) {
				this.markers = []
				const markers = []
				for (let i = 0, j = data.length; i < j; i++) {
					const item = data[i]
					if (!item.lat) {
						continue
					}
					const latLng = {
						lat: item.lat,
						lng: item.lng
					}
					// if (i === 0) {
					// 	this.lat = latLng.lat
					// 	this.lng = latLng.lng
					// }
					let iconPath
					if (item.num >= 99) {
						iconPath =
							`${myConfig.app.baseUrl}/file/download/static/iot/uni/map/numsImage/${this.$store.state.themeConfig.theme}/local_99.png`
					} else {
						iconPath =
							`${myConfig.app.baseUrl}/file/download/static/iot/uni/map/numsImage/${this.$store.state.themeConfig.theme}/local_${item.num}.png`
					}
					const marker = {
						id: markers.length,
						width: 35,
						height: 35,
						latitude: latLng.lat,
						longitude: latLng.lng,
						iconPath: iconPath,
						provinceId: item.provinceId,
						cityId: item.cityId,
					}
					markers.push(marker)
				}
				this.markers = markers
			},
			setPointMarkers(data) {
				this.deviceList = data
				if (data.length > 1000) {
					this.showLoadingMuchTip = true
				} else {
					this.doSetPointMarkers()
				}
			},
			doSetPointMarkers() {
				this.showLoadingMuchTip = false
				showLoading(this.$t('loading'), true)
				this.markers = []
				const markers = []
				// console.log('-----------')
				// console.log(this.deviceList)
				for (let i = 0, j = this.deviceList.length; i < j; i++) {
					const item = this.deviceList[i]
					if (!item.latitude) {
						continue
					}
					const marker = {
						id: markers.length,
						markerId:item.id,
						width: 30,
						height: 30,
						latitude:item.latitude,
						longitude: item.longitude,
						iconPath: item.iconImage,
						deviceName: item.name,
						deviceCore: item.code,
					}
					markers.push(marker)
				}
				this.markers = markers
				setTimeout(() => {
					hideLoading()
				}, 0)
			},
			markertap(e) {
				this.markerId = e.detail.markerId
				// switch (this.showMode) {
				// 	case 'area':
				// 		this.markertapAreaMode()
				// 		break
				// 	case 'geo':
				// 	case 'point':
				// 		this.markertapPointOrGeoMode()
				// 		break
				// }
				this.markertapPointOrGeoMode()
			},
			mapTap(e) {
				this.lat = e.detail.latitude
				this.lng = e.detail.longitude
				if (this.showMode === 'geo') {
					this.listDeviceGEO()
				}
			},
			markertapAreaMode() {
				const {
					provinceId,
					cityId
				} = this.markers[this.markerId]
				this.provinceId = provinceId
				this.cityId = cityId
				this.isShowDeviceList = true
				this.$emit('is-show-nav', false);
				this.currentPage = 1
			},
			markertapPointOrGeoMode() {
				// console.log('--------markertapPointOrGeoMode')
				// console.log(this.markers[this.markerId])
				const {
					markerId,
					deviceCore,
					deviceName
				} = this.markers[this.markerId]
				const component = storage.getDeviceNavigationComponent()
				uni.navigateTo({
					url: `/pages/deviceNavigation/deviceNavigation?id=${markerId}&code=${deviceCore}&name=${deviceName}&component=${component}`
				})
			},

			pageGetDevice() {
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.pageGetAllDevice({
							provinceId: this.provinceId,
							cityId: this.cityId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
						break
					case 'company':
						api = iotDeviceApi.pageGetDeviceByCompany({
							companyId: this.companyId,
							provinceId: this.provinceId,
							cityId: this.cityId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
						break
					case 'dept':
						api = iotDeviceApi.pageGetDeviceByDept({
							deptId: this.deptId,
							provinceId: this.provinceId,
							cityId: this.cityId,
							status: this.statusList[this.statusIndex].value,
							productId: this.productId,
							seriesId: this.seriesId,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
						break
					default:
						api = iotDeviceBelongApi.pageGetBelongDevice({
							provinceId: this.provinceId,
							cityId: this.cityId,
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
							currentPage: this.currentPage,
							pageSize: this.pageSize
						})
				}

				api.then(res => {
					const {
						data
					} = res
					if (data) {
						this.totalDeviceNum = data.total
						this.mescroll.endByPage(data.data.length, data.total)
						this.$set(this.deviceList, data.currentPage - 1, data.data)
						this.currentPage = data.currentPage + 1
					}
				})
			},
			listDevice() {
				showLoading(this.$t('loading'), true)
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.listAllDevice({
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
						})
						break
					case 'company':
						api = iotDeviceApi.listDeviceByCompany({
							companyId: this.companyId,
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
						})
						break
					case 'dept':
						api = iotDeviceApi.listDeviceByDept({
							deptId: this.deptId,
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
						})
						break
					default:
						api = iotDeviceBelongApi.listBelongDevice({
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
						})
				}

				api.then((res) => {
					const {
						data
					} = res
					if (data) {
						this.resetMapParam()
						this.setPointMarkers(data)
						setTimeout(() => {
							hideLoading()
						}, 0)
					}
				})
			},
			listDeviceGEO() {
				showLoading(this.$t('loading'), true)
				const latLng = {
					lat: this.lat,
					lng: this.lng
				}
				let api
				switch (this.websiteModel) {
					case 'system':
						api = iotDeviceApi.listAllDeviceGEO({
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
							lat: latLng.lat,
							lng: latLng.lng,
							geoHash: 3
						})
						break
					case 'company':
						api = iotDeviceApi.listDeviceByCompanyGEO({
							companyId: this.companyId,
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
							lat: latLng.lat,
							lng: latLng.lng,
							geoHash: 3
						})
						break
					case 'dept':
						api = iotDeviceApi.listDeviceByDeptGEO({
							deptId: this.deptId,
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
							lat: latLng.lat,
							lng: latLng.lng,
							geoHash: 3
						})
						break
					default:
						api = iotDeviceBelongApi.listBelongDeviceGEO({
							productId: this.productId,
							seriesId: this.seriesId,
							status: this.statusList[this.statusIndex].value,
							lat: latLng.lat,
							lng: latLng.lng,
							geoHash: 3
						})

				}

				api.then((res) => {
					const {
						data
					} = res
					if (data) {
						this.markers = []
						this.setPointMarkers(data)
						setTimeout(() => {
							hideLoading()
						}, 0)

					}
				})
			},
			getScale() {
				return new Promise((resolve) => {
					mapContext.getScale({
						success: (e) => {
							resolve(e)
						}
					})
				})
			},
			regionchange() {
				if (this.showMode === 'area') {
					mapContext.getScale({
						success: (e) => {
							if (e.scale < 6) {
								this.listProvinceNum()
							} else if (e.scale >= 6) {
								this.listCityNum()
							}
						}
					})
				}
			},
			hideDeviceList() {
				this.isShowDeviceList = false
				this.$emit('is-show-nav', true);
				this.productIndex = 0
				this.currentPage = 1
				this.deviceList = []
			}
		}
	}
</script>

<style scoped>
	.ztnCustom-background-color {
		position: fixed;
		width: 100vw;
		height: 100vh;
		top: 0;
		z-index: 998;
		background: rgba(0, 0, 0, 0.6);

	}

	.ztnCustom-hideIcon {
		height: 45rpx;
		text-align: center;
	}
</style>
